from jinja2 import Template
import os

from src.settings import STATIC_ROOT


class TemplateRender:
    source = None

    def __init__(self, **kwargs):
        self.source = kwargs.get("template")

    def render(self, **kwargs):
        """
        渲染模板
        :param kwargs:
        :return:
        """
        render_data = kwargs.get("data")
        tpl = Template(source=self.source)
        result = tpl.render(**render_data)
        return result

    def save_render(self, **kwargs):
        """
        保存渲染结果
        :param kwargs:
        :return:
        """
        file_name = kwargs.get("file_name")
        render_data = kwargs.get("data")
        result = self.render(data=render_data)
        file_path = os.path.join(STATIC_ROOT, file_name)
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(result)


if __name__ == '__main__':
    with open("../../static/template.tpl", 'r', encoding="utf-8") as f:
        template = f.read()
        data = {"params": ["name", "phone"]}
        print(data)
        TemplateRender(template=template).save_render(file_name="result.py", data=data)
